package com.vic.test.thread;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 自己实现hreadLocal
 * @author VIC
 *
 */
public class MyThreadLocal<T> {

	private Map<Thread, T> container = Collections.synchronizedMap(new HashMap<Thread, T>());
	
	public MyThreadLocal() {
		
	}
	
	
	public void set(T value){
		container.put(Thread.currentThread(), value);
	}
	
	
	public T get(){
		Thread t = Thread.currentThread();
		T value = container.get(t);
		if(value == null && !container.containsKey(t)) {
			value = initialValue();
			container.put(t, value);
		}
		return value;
	}
	
	public void remove(){
		container.remove(Thread.currentThread());
	}
	
	protected T initialValue() {
		return null;
	}
}
